package dingtalk.dfau.service.impl;

import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiFileUploadSingleRequest;
import com.dingtalk.api.request.OapiProcessinstanceCspaceInfoRequest;
import com.dingtalk.api.response.OapiFileUploadSingleResponse;
import com.dingtalk.api.response.OapiProcessinstanceCspaceInfoResponse;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.taobao.api.internal.util.WebUtils;
import dingtalk.dfau.service.DingTalkFileUploader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class DingTalkFileUploaderimpl {
    @Resource
    private DingTalkFileUploader dingTalkFileUploader;
    private static final String GET_ACCESS_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
    private static final String UPLOAD_FILE_URL = "https://oapi.dingtalk.com/topapi/processinstance/upload_attachment";

    private String appKey;
    private String appSecret;

    public DingTalkFileUploaderimpl(String appKey, String appSecret) {
        this.appKey = "dinge2exyxzsppghht13";
        this.appSecret = "gw0HNsZrxau65fj52HEVsnyYGeH6n7q31H6IonOTSS6QPG-nBw9CyeyGSN7305WU";
    }

    // 获取access_token
    public String getAccessToken() throws IOException {
        String url = GET_ACCESS_TOKEN_URL + "?appkey=" + appKey + "&appsecret=" + appSecret;
        String response = sendGetRequest(url);
        JSONObject json = JSONObject.parseObject(response);
        System.out.println("access_token: " + json.getString("access_token"));
        return json.getString("access_token");

    }


    public Long getSpaceId() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/cspace/info");
        OapiProcessinstanceCspaceInfoRequest req = new OapiProcessinstanceCspaceInfoRequest();
// 用户的钉钉id
        req.setUserId("xxxxxxxxx");
        OapiProcessinstanceCspaceInfoResponse rsp = null;
        try {
            rsp = client.execute(req, getAccessToken());
        } catch (ApiException | IOException e) {
            System.out.println("获取钉盘Id失败！原因");
        }
        if (Objects.isNull(rsp)) {
            return null;
        }
        return rsp.getResult().getSpaceId();
    }

    public String getUploadUrl() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/files/get");
        OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
        OapiFileUploadSingleResponse response;
        try {
            response = client.execute(request, getAccessToken());
            System.out.println(response.getBody());
            return response.getBody();
        } catch (ApiException | IOException e) {
            System.out.println("获取上传文件地址失败！原因");
        }
        return null;
    }

    // 上传文件
    public String uploadFile(String accessToken, String filePath) throws IOException, ApiException {
        OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
        request.setFileSize(45L);
        request.setAgentId("83642");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?"+ WebUtils.buildQuery(request.getTextParams(),"utf-8"));
        // 必须重新new一个请求
        request = new OapiFileUploadSingleRequest();
        request.setFile(new FileItem(filePath));
        OapiFileUploadSingleResponse response = client.execute(request,accessToken);
        System.out.println(response.getBody());
        return response.getBody();
    }

    // 发送GET请求
    private String sendGetRequest(String url) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        return readResponse(con);
    }

    // 读取响应
    private String readResponse(HttpURLConnection con) throws IOException {
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

    public static void main(String[] args) {
        String appKey = "dinge2exyxzsppghht13";
        String appSecret = "gw0HNsZrxau65fj52HEVsnyYGeH6n7q31H6IonOTSS6QPG-nBw9CyeyGSN7305WU";
        String filePath = "E:\\测试.xlsx";

        DingTalkFileUploaderimpl uploader = new DingTalkFileUploaderimpl(appKey, appSecret);
        try {
            String accessToken = uploader.getAccessToken();
            String uploadUrl = uploader.getUploadUrl();
            Long spaceId = uploader.getSpaceId();
            String result = uploader.uploadFile(accessToken, filePath);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }
}
